﻿using AntdUI;
using ImportPlcPointPosition.Controls.Base;
using ImportPlcPointPosition.Enums;
using ImportPlcPointPosition.Forms;
using ImportPlcPointPosition.Models.Table;
using ImportPlcPointPosition.Utils;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;

namespace ImportPlcPointPosition.Controls.Pages
{
    public partial class PlcBlockPage : BaseUserControl {
        private readonly SqlSugarClient MesDBClient = SqlSugarHelper.MesDB;

        public PlcBlockPage() {
            InitializeComponent();
            this.Load += PlcBlockPage_Load;
            txtSearch.TextChanged += TxtSearch_TextChanged;
        }

        #region Methods

        /// <summary>
        /// 初始化表格
        /// </summary>
        private void InitTable() {
            tablePlcBlock.EditMode = TEditMode.None;
            tablePlcBlock.Columns = new ColumnCollection()
            {
                new ColumnCheck("IsCheck").SetAlign(),
                new Column("Id", "ID").SetAlign().SetEditable(),
                new Column("ProductionLineCode", "产线编号").SetAlign().SetEditable(),
                new Column("WorkstationCode", "工站编号").SetAlign().SetEditable(),
                new Column("PlcRemark", "PLC备注").SetAlign().SetEditable(),
                new Column("BlockDb", "数据块").SetAlign(),
                new Column("WriteFromCellText", "写入方").SetAlign().SetEditable(),
                new Column("ModuleCellText", "模块").SetAlign(),
                new Column("Remark", "备注(Cn)").SetAlign(),
                new Column("Remark_En", "备注(En)").SetAlign(),
                new Column("Sequence", "排序").SetAlign(),
                new Column("Operate", "操作").SetAlign().SetFixed(),
            };
            tablePlcBlock.Bordered = true;
            tablePlcBlock.EnableHeaderResizing = false;
            tablePlcBlock.EmptyHeader = true;
            tablePlcBlock.Gap = 6;
            tablePlcBlock.EditMode = TEditMode.Click;
            tablePlcBlock.CellButtonClick += Table1_CellButtonClick;
        }

        private void LoadQuerySelect() {
            this.selLineCode.Items.Clear();
            var lst = MesDBClient.Queryable<PlcConfig>().ToList();
            this.selLineCode.Items.AddRange(lst.Select(o => o.ProductionLineCode).Distinct().ToArray());
        }

        /// <summary>
        /// 加载数据列表
        /// </summary>
        private void LoadDataTable() {
            string search = txtSearch.Text;
            var DataTableSource = new BindingList<PlcBlockDb>();
            var lst = MesDBClient.Queryable<PlcBlockDb>()
                .InnerJoin<PlcConfig>((a, b) => a.PlcId == b.Id)
                .WhereIF(!string.IsNullOrEmpty(this.selLineCode.SelectedValue?.ToString()), (a, b) => b.ProductionLineCode == this.selLineCode.SelectedValue.ToString())
                .WhereIF(!search.IsNullOrEmpty(), (a, b) => b.WorkstationCode.Contains(search))
                .OrderBy((a, b) => b.ProductionLineCode)//排序
                .OrderBy((a,b) => a.Sequence)
                                                        //.OrderBy((a, b) => b.WorkstationCode)//排序
                .Select((a, b) => new PlcBlockDb() { ProductionLineCode = b.ProductionLineCode, WorkstationCode = b.WorkstationCode, PlcRemark = b.Remark }, true)
                .ToList();
            foreach (var item in lst) {
                DataTableSource.Add(item);
            }
            this.tablePlcBlock.Binding(DataTableSource);
        }

        #endregion


        #region Events

        /// <summary>
        /// 页面初始化事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlcBlockPage_Load(object sender, EventArgs e) {
            InitTable();
            LoadDataTable();
            LoadQuerySelect();
        }

        /// <summary>
        /// 新增按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e) {
            BlockDbEditForm form = new BlockDbEditForm();
            DialogResult dialogResult = form.ShowDialog();
            if (dialogResult == DialogResult.OK) {
                base.MessageSuccess("新增成功！");
                LoadDataTable();
            }
        }

        /// <summary>
        /// 单元格操作按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Table1_CellButtonClick(object sender, TableButtonEventArgs e) {
            var item = e.Record as PlcBlockDb;
            if (string.IsNullOrEmpty(e.Btn.Id)) {
                return;
            }
            switch ((eOperateBtnType)Enum.Parse(typeof(eOperateBtnType), e.Btn.Id)) {
                case eOperateBtnType.AddBtn:
                    break;
                case eOperateBtnType.EditBtn:
                    break;
                case eOperateBtnType.DeleteBtn:
                    var result = base.MessageBoxShow($"确认要删除选择的数据吗？", TType.Warn);
                    if (result == DialogResult.OK) {
                        //删除DB块表
                        MesDBClient.Deleteable<PlcBlockDb>().WhereColumns(item, a => new { a.Id }).ExecuteCommand();
                        //删除全部关联[DB块]的点位
                        MesDBClient.Deleteable<CksPlcDataPosition>()
                            .Where(a => a.PlcId == item.PlcId && a.BlockDbId == item.Id)
                            .ExecuteCommand();
                        base.MessageSuccess("操作成功！");
                        LoadDataTable();
                    }
                    break;
                case eOperateBtnType.SaveBtn:
                    var Exists = MesDBClient.Queryable<PlcBlockDb>().Where(a => a.Id == item.Id).Any();
                    if (Exists) {
                        //更新DB块表
                        MesDBClient.Updateable(item).Where(a => a.Id == item.Id).ExecuteCommand();
                        //更新全部关联[DB块]的点位
                        MesDBClient.Updateable<CksPlcDataPosition>()
                            .SetColumns(a => a.BlockDb == item.BlockDb)
                            .Where(a => a.BlockDbId == item.Id)
                            .ExecuteCommand();
                        base.MessageSuccess("保存成功！");
                    }
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 搜索框事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtSearch_TextChanged(object sender, EventArgs e) {
            LoadDataTable();
        }

        /// <summary>
        /// 刷新按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e) {
            LoadDataTable();
        }

        private void selLineCode_SelectedIndexChanged(object sender, IntEventArgs e) {
            LoadDataTable();
        }

        /// <summary>
        /// 保存全部按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveAll_Click(object sender, EventArgs e) {
            var list = tablePlcBlock.DataSource as BindingList<PlcBlockDb>;
            if (list.Count > 0) {
                foreach (var item in list) {
                    if (item.Id != 0) {
                        var Exists = MesDBClient.Queryable<PlcBlockDb>().Where(a => a.Id == item.Id).Any();
                        if (Exists) {
                            //更新DB块表
                            MesDBClient.Updateable(item).Where(a => a.Id == item.Id).ExecuteCommand();
                            //更新全部关联[DB块]的点位
                            MesDBClient.Updateable<CksPlcDataPosition>()
                                .SetColumns(a => a.BlockDb == item.BlockDb)
                                .Where(a => a.BlockDbId == item.Id)
                                .ExecuteCommand();
                        }
                    }
                }
                base.MessageSuccess("全部保存成功！");
                LoadDataTable();
            }
        }


        private void btnDeleteAll_Click(object sender, EventArgs e) {

            var list = tablePlcBlock.DataSource as BindingList<PlcBlockDb>;
            if (list.Count > 0) {
                var result = base.MessageBoxShow($"确认要删除选择的数据吗？", TType.Warn);
                if (result == DialogResult.OK) {
                    foreach (var item in list) {
                        //删除DB块表
                        MesDBClient.Deleteable<PlcBlockDb>().WhereColumns(item, a => new { a.Id }).ExecuteCommand();
                        //删除全部关联[DB块]的点位
                        MesDBClient.Deleteable<CksPlcDataPosition>()
                            .Where(a => a.PlcId == item.PlcId && a.BlockDbId == item.Id)
                            .ExecuteCommand();
                    }
                    base.MessageSuccess("操作成功！");
                    LoadDataTable();
                }
            } else {
                base.MessageError("请至少选择一条数据！");
            }
        }

        #endregion

        
    }
}
